package customerService

import (
	"context"
	"math"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/types"
	"gitee.com/liuxuezhan/ar-platform/admin-api/pkg/code"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/setting/client/customerservicegroup"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/setting/rpc"
	"github.com/zeromicro/go-zero/core/logc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CustomerServiceListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 客服管理列表
func NewCustomerServiceListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CustomerServiceListLogic {
	return &CustomerServiceListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CustomerServiceListLogic) CustomerServiceList(req *types.CustomerServiceListReq) (resp *types.CustomerServiceListData, err error) {
	list := make([]types.CustomerServiceListItem, 0)
	resp = &types.CustomerServiceListData{
		List: list,
		Pagination: types.Pagination{
			PageSize:  int32(req.Size),
			Page:      int32(req.Page),
			Total:     0,
			TotalPage: 0,
		},
	}

	u, err := l.svcCtx.SettingService.CustomerService.CustomerServiceList(l.ctx, &customerservicegroup.CustomerServiceListReq{
		Page:                req.Page,
		Size:                req.Size,
		MerchantId:          1,                                                                    // 商户ID
		CustomerServiceType: rpc.CustomerServiceType(req.CustomerServiceType.CustomerServiceType), // 客服类型
		CommunicationType:   rpc.CommunicationType(req.CommunicationType.CommunicationType),
		Status:              -1,
	})

	if err != nil {
		logc.Error(l.ctx, "CustomerServiceList err:", err)
		return nil, err
	}

	if u.Code != int64(code.SettingRpcSuccessful.Code()) {
		return nil, code.BusinessFailure
	}

	for _, v := range u.Data.List {
		list = append(list, types.CustomerServiceListItem{
			Id:                   v.Id,
			MerchantId:           v.MerchantId,
			CustomerServiceType:  v.CustomerServiceType,
			CommunicationType:    v.CommunicationType,
			Title:                v.Title,
			CommunicationAddress: v.CommunicationAddress,
			Sort:                 v.Sort,
			Status:               v.Status,
			UpdatedAt:            v.UpdatedAt,
		})
	}

	resp.List = list
	resp.PageSize = int32(req.Size)
	resp.Page = int32(req.Page)
	resp.Total = u.Data.Count
	resp.TotalPage = int64(math.Ceil(float64(u.Data.Count) / float64(req.Size)))

	return resp, nil
}
